//
//  StatusTool.m
//  Weibo
//
//  Created by Anasue on 9/21/15.
//  Copyright (c) 2015 Anasue. All rights reserved.
//

#import "StatusTool.h"
#import "MJExtension.h"
#import "HttpTool.h" 
#import "FMDB.h"
#import "Status.h"

@implementation StatusTool

static FMDatabase *_db;
+ (void)initialize
{
    NSString *filename = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject]stringByAppendingPathComponent:@"status.sqlite"];
    _db = [FMDatabase databaseWithPath:filename];
    if ([_db open]) {
        BOOL result = [_db executeUpdate:@"CREATE TABLE IF NOT EXISTS t_home_status (id integer PRIMARY KEY AUTOINCREMENT,access_token text NOT NULL,status_idstr TEXT NOT NULL,status_dict blob NOT NULL);"];
        if (result) {
            Log(@"创建成功");
        }else{
            Log(@"创建失败");
        }
    }
}

+ (void)homeStatusesWithParams:(HomeStatusesParam *)params success:(void(^)(HomeStatusesResult *))success failure:(void (^)(NSError *))failure
{
    NSArray *chacheHomeStatuses = [self chacheHomeStatusesWithParam:params];
    if (chacheHomeStatuses.count != 0) {
        if (success) {
            HomeStatusesResult *result = [[HomeStatusesResult alloc]init];
            result.statuses = chacheHomeStatuses;
            success(result);
        }
    }else{
//    [self getWithUrl:@"https://api.weibo.com/2/statuses/home_timeline.json" param:params resultClass:[HomeStatusesResult class] success:success failure:failure];
        
        NSDictionary *param = [params keyValues];
        [HttpTool get:@"https://api.weibo.com/2/statuses/home_timeline.json" params:param success:^(id responseObj) {
            NSArray *statusDictArray = responseObj[@"statuses"];
            [self saveStatusDictArray:statusDictArray accessToken:params.access_token];
            if (success) {
                HomeStatusesResult *result = [HomeStatusesResult objectWithKeyValues:responseObj];
                success(result);
            }
        } failure:^(NSError *error) {
            if (failure) {
                failure(error);
            }
        }];
    }
}

+ (NSArray *)chacheHomeStatusesWithParam:(HomeStatusesParam *)param
{
    NSMutableArray *statuses = [NSMutableArray array];
    FMResultSet *resultSet = nil;
    if (param.since_id) {
        resultSet = [_db executeQuery:@"SELECT * FROM t_home_status WHERE access_token = ? AND status_idstr > ? ORDER BY status_idstr DESC limit ?;",param.access_token,param.since_id,param.count];
    }else if(param.max_id){
        resultSet = [_db executeQuery:@"SELECT * FROM t_home_status WHERE access_token = ? AND status_idstr <= ? ORDER BY status_idstr DESC limit ?;",param.access_token,param.max_id,param.count];
    }else{
        resultSet = [_db executeQuery:@"SELECT * FROM t_home_status WHERE access_token = ? ORDER BY status_idstr DESC limit ?;",param.access_token,param.count];
    }
    while (resultSet.next) {
        NSData *data = [resultSet objectForColumnName:@"status_dict"];
        NSDictionary *statusDict = [NSKeyedUnarchiver unarchiveObjectWithData:data];
        Status *status = [Status objectWithKeyValues:statusDict];
        [statuses addObject:status];
    }
    return statuses;
}

+ (void)saveStatusDictArray:(NSArray *)statusDictArray accessToken:(NSString *)accessToken
{
    for (NSDictionary *statusDict in statusDictArray) {
        NSData *data = [NSKeyedArchiver archivedDataWithRootObject:statusDict];
        [_db executeUpdate:@"INSERT INTO t_home_status (access_token,status_idstr,status_dict) VALUES (?,?,?)",accessToken,statusDict[@"idstr"],data];
    }
}

+ (void)sendStatusesWithParams:(SendStatusParam *)params success:(void(^)(SendStatusResult *))success failure:(void (^)(NSError *))failure
{
    
    [self postWithUrl:@"https://api.weibo.com/2/statuses/update.json" param:params resultClass:[SendStatusResult class] success:success failure:failure];
}

+ (void)commentsWithParams:(CommentParam *)params success:(void(^)(CommentResult *))success failure:(void (^)(NSError *))failure
{
    [self getWithUrl:@"https://api.weibo.com/2/comments/show.json" param:params resultClass:[CommentResult class] success:success failure:failure];
}

+ (void)retweetedWithParams:(RetweetedParam *)params success:(void(^)(RetweetedResult *))success failure:(void (^)(NSError *))failure
{
    [self getWithUrl:@"https://api.weibo.com/2/statuses/repost_timeline.json" param:params resultClass:[RetweetedResult class] success:success failure:failure];
}


@end
